package com.game.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.lang.NonNull;

import java.util.ArrayList;
import java.util.List;

/// 添加MongoDB配置
@Configuration
public class MongoConfig {

    @Bean
    public MongoTemplate mongoTemplate(MongoDatabaseFactory databaseFactory) {
        // 配置序列化选项以确保类型安全
        return new MongoTemplate(databaseFactory);
    }

    @Bean
    public MongoCustomConversions mongoCustomConversions() {
        List<Converter<?, ?>> converters = new ArrayList<>();
        converters.add(new StringToIntegerConverter());
        converters.add(new IntegerToStringConverter());
        return new MongoCustomConversions(converters);
    }

    @WritingConverter
    public static class StringToIntegerConverter implements Converter<String, Integer> {
        @Override
        public Integer convert(@NonNull String source) {
            return Integer.valueOf(source);
        }
    }

    @ReadingConverter
    public static class IntegerToStringConverter implements Converter<Integer, String> {
        @Override
        public String convert(@NonNull Integer source) {
            return String.valueOf(source);
        }
    }
}